﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using DDD.Core;

namespace DDD.OpenTK {
    /// <summary>
    /// <see cref="FragmentShader"/>クラスに拡張メソッドを追加するクラス
    /// </summary>
    public static class FragmentShaderExtensions {

        /// <summary>
        /// フラグメント・シェーダーのコンパイルします
        /// </summary>
        /// <param name="fs">フラグメントシェーダー</param>
        public static void Compile (this FragmentShader fs) {
            var cache = Graphics3DExtensions.GetGLCache ();
            var id = cache[fs];
            if (id > 0) {
                return;
            }

            id = GL.CreateShader (ShaderType.FragmentShader);
            if (id == 0) {
                throw new InvalidOperationException ("glCreateShader was failed");
            }

            GL.ShaderSource (id, fs.Source);
            GL.CompileShader (id);
            if (id == 0) {
                throw new InvalidOperationException ("glCreateShader was failed");
            }

            fs.SetLog (GL.GetShaderInfoLog (id));

            int status;
            GL.GetShader (id, ShaderParameter.CompileStatus, out status);
            if (status <= 0) {
                throw new InvalidOperationException ("Compile of FragmentShader was Failed, log=" + fs.CompileLog);
            }

            cache.Add (fs, id);
        }
    }
}
